/*
 * @Author: ydli
 * @LastEditTime: 2021-05-02 20:37:09
 * @Description: 
 */
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import store from '../store';
import http from '../util/http';
// import store from '../store';
import Home from '../view/Home.vue';
import Login from '../view/Login.vue';
import Signup from '../view/Signup.vue';
import ColumnDetail from '../view/ColumnDetail.vue';
import CreatePost from '../components/CreatePost.vue';
// import PostsDetail from '../view/postDetail.vue';
import GlobalHeader from '../components/GlobalHeader.vue';
import GlobalFooter from '../components/GlobalFooter.vue';
const routerHistory = createWebHistory();
const routes: RouteRecordRaw[] = [
    {
        path: '/',
        name: 'home',
        components: {
            GlobalHeader,
            default: Home,
            GlobalFooter
        },
    },
    {
        path: '/login',
        name: 'login',
        components: {
            GlobalHeader,
            default: Login,
            GlobalFooter
        },
        meta: { redirectAlreadyLogin: true }
    },
    {
        path: '/signup',
        name: 'signup',
        components: {
            GlobalHeader,
            default: Signup,
            GlobalFooter
        },
        meta: { redirectAlreadyLogin: true }
    },
    {
        path: '/create',
        name: 'create',
        components: {
            GlobalHeader,
            default: CreatePost,
            GlobalFooter,
        },
        meta: { requiredLogin: true }
    },
    {
        path: '/column/:id',
        name: 'column',
        components: {
            GlobalHeader,
            default: ColumnDetail,
            GlobalFooter
        },
    },
    // {
    //     path: '/posts/:id',
    //     name: 'posts',
    //     components: {
    //         GlobalHeader,
    //         default: PostsDetail,
    //         GlobalFooter
    //     },
    // }
]

const router = createRouter({
    history: routerHistory,
    routes
})

// 全局前置守卫 - 权限验证
router.beforeEach((to, from, next) => {
    const { user, token } = store.state;
    const { requiredLogin, redirectAlreadylogin } = to.meta;
    if (!user.isLogin) {
        if (token) {
            http.defaults.headers.common['Authorization'] = `Bearer ${token}`;
            store.dispatch('fetchCurrentUser').then(() => {
                if(redirectAlreadylogin){
                    next('/');
                }else{
                    next();
                }
            }).catch(e => {
                console.error(e);
                store.commit('logout');
                next('login');
            })
        } else {
            if(requiredLogin){
                // 需要登陆才能访问
                next('login');
            }else{
                next();
            }
        }
    } else {
        // 已登陆
        if (redirectAlreadylogin) {
            next('/');
        } else {
            next();
        }
    }
})


export default router;